import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
// 引入2D渲染器
import { CSS2DRenderer } from "three/addons/renderers/CSS2DRenderer.js";
export let scene, camera, renderer, controls, css2drenderer;

//初始化
(function init() {
  scene = new THREE.Scene();
  camera = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    0.1,
    1000
  );
  camera.position.z = 0.1;
  renderer = new THREE.WebGLRenderer({ antialias: true });
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);
})();

//控制器
(function createControls() {
  controls = new OrbitControls(camera, renderer.domElement);
})();

//坐标轴辅助线
(function createHelper() {
  const axesHelper = new THREE.AxesHelper(5);
  scene.add(axesHelper);
})();

//适配
(function resizeRender() {
  window.addEventListener("resize", () => {
    renderer.setSize(window.innerWidth, window.innerHeight);
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    // 适配2d 渲染器
    css2drenderer.setSize(window.innerWidth, window.innerHeight);
  });
})();

//2d渲染器
(function create2dRenderer() {
  css2drenderer = new CSS2DRenderer();
  css2drenderer.setSize(window.innerWidth, window.innerHeight);
  css2drenderer.domElement.style.position = "fixed";
  css2drenderer.domElement.style.left = "0";
  css2drenderer.domElement.style.top = "0";
  css2drenderer.domElement.style.pointerEvents = "none";
  document.body.appendChild(css2drenderer.domElement);
})();

//动画函数
(function animation() {
  renderer.render(scene, camera);
  controls.update();
  css2drenderer.render(scene, camera);
  requestAnimationFrame(animation);
})();
